<script setup>
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  LegendComponent,
  PieChart
])
import { onBeforeUnmount, onMounted, reactive, watch } from 'vue'
import { chartsColors } from '@/utils/config.js'
import { formatNumber } from '@/utils/unit.js'

let chartInstance = null
const props = defineProps(['data', 'eid'])
const arrayDate = ref(props.data)
const option = reactive({
  color: chartsColors,
  tooltip: {
    trigger: 'item',
    show: false,
    textStyle: {
      fontSize: 10
    }
  },
  title: {},
  grid: {
    bottom: '20%' // 下边距
  },
  series: [
    {
      name: '',
      type: 'pie',
      center: ['50%', '50%'],
      radius: ['45%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 0,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      labelLine: {
        show: false
      },
      data: arrayDate.value.seriesData
    }
  ]
})

const hasData = ref(false)
const centerText = reactive({
  title: '工单总数',
  value: arrayDate.value.total || '0',
  unit: '件'
})
let carouselInterval = null
let currentIndex = -1
const pauseCarousel = () => {
  if (carouselInterval) {
    handleDownplay(currentIndex)
    clearInterval(carouselInterval)
    carouselInterval = null
    currentIndex = -1
  }
}

const resumeCarousel = () => {
  if (!carouselInterval) {
    carouselInterval = setInterval(highlightNextItem, 5000)
  }
}
const handleDownplay = (index) => {
  chartInstance.dispatchAction({
    type: 'downplay',
    seriesIndex: 0,
    dataIndex: index
  })
}
const highlightNextItem = () => {
  const dataLen = option.series[0].data.length
  // 取消之前高亮的图形
  handleDownplay(currentIndex)
  currentIndex = (currentIndex + 1) % dataLen
  // 高亮当前图形
  chartInstance.dispatchAction({
    type: 'highlight',
    seriesIndex: 0,
    dataIndex: currentIndex
  })
  let item = option.series[0].data[currentIndex]
  let temp = formatNumber(item.value)
  centerText.title = item.name
  centerText.value = temp.value
  centerText.unit = temp.unit
}

const handleLabelClick = (params) => {
  let index = option.series[0].data.findIndex(
    (item) => item.name === params.label
  )
  let data = option.series[0].data[index]
  handleClick({
    dataIndex: index,
    ...data
  })
}

defineExpose({
  handleLabelClick
})

onMounted(() => {
  chartInstance = echarts.init(document.getElementById(props.eid))
  updateChart()
  window.addEventListener('resize', canalDebounce)
  pauseCarousel()
  resumeCarousel()
  // 添加点击事件监听
  chartInstance.on('click', (params) => {
    handleClick(params)
  })
})

const handleClick = (params) => {
  pauseCarousel()
  chartInstance.dispatchAction({
    type: 'downplay',
    seriesIndex: 0,
    dataIndex: currentIndex
  })
  currentIndex = params.dataIndex
  chartInstance.dispatchAction({
    type: 'highlight',
    seriesIndex: 0,
    dataIndex: currentIndex
  })
  let temp = formatNumber(params.value)
  centerText.title = params.name
  centerText.value = temp.value
  centerText.unit = temp.unit
  // 恢复轮播
  setTimeout(() => {
    resumeCarousel()
  }, 3000)
}

watch(
  () => props,
  (newVal) => {
    hasData.value =
      !newVal.data.seriesData || newVal.data.seriesData.length === 0
    option.series[0].data = newVal.data.seriesData
    updateChart()
    pauseCarousel()
    resumeCarousel()
  },
  { deep: true }
)

//页面销毁前，销毁事件和实例
onBeforeUnmount(() => {
  window.removeEventListener('resize', canalDebounce)
  pauseCarousel()
})

const updateChart = () => {
  if (chartInstance) {
    chartInstance.setOption(option)
  }
}
const resizeHandler = () => {
  chartInstance.resize()
}
//设置防抖，保证无论拖动窗口大小，只执行一次获取浏览器宽高的方法
const debounce = (fun, delay) => {
  let timer
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fun()
    }, delay)
  }
}
const canalDebounce = debounce(resizeHandler, 500)
</script>

<template>
  <section class="flex justify-around w-full p-0 relative">
    <div
      class="absolute w-full h-full flex flex-col items-center justify-center box-border left-0 top-0"
    >
      <template v-if="hasData">
        <p class="text-12px font-400 leading-17px text-#71747A">暂无数据</p>
      </template>
      <template v-else>
        <p class="text-12px font-400 leading-17px text-#71747A">
          {{ centerText.title }}
        </p>
        <p class="text-18px font-700 leading-20px text-#1E2226 font-din">
          {{ centerText.value }}
        </p>
        <p class="text-12px font-400 leading-17px text-#71747A">
          {{ centerText.unit }}
        </p>
      </template>
    </div>
    <div :id="props.eid" class="flex-1 h-30vh z-90" />
  </section>
</template>

<style scoped>
p {
  margin: 0;
}
</style>
